
from flask import Blueprint,request,jsonify,redirect
from flask import current_app as app
from utils.db import db
from utils.comm import get_data
from werkzeug.security import generate_password_hash,check_password_hash

from flask_mail import Mail,Message

bp_users = Blueprint('users',__name__)


#   分装一个发送短信方法
def send_mail(title,email,content):
    mail = Mail(app)
    msg = Message(title,sender='l1208007330@163.com',recipients=[email])#发件人，收件人
    msg.html = content
    mail.send(msg)

@bp_users.route('/reg/',methods=['POST'])
def reg():
    

        #获取前端传递数据
        data = get_data()
        #添加到数据库
        sql = "insert into users(`nikename`,`email`,`password`) values('%s','%s','%s')"%(data['nikename'],data['email'],generate_password_hash(data['password']))
        print(sql)
        db.insert(sql)

        #发送邮件 给一个地址去验证
        send_mail('欢迎使用，不要刻意',data['email'],"欢迎使用，点击以下<a href='http://localhost:5000/reg/validEmail/?email="+data['email']+"'>链接</a>验证")
    
        return jsonify({'code':200})

@bp_users.route('/validEmail/')
def validEmail():
    #获取email
    email = request.args.get('email')
    #更新状态为1
    sql  = "update users set status=1 where email='%s'"%(email)
    db.update(sql)
    #改变后返回主页地址
    return redirect('http://localhost:8888')


#课程分类
@bp_users.route('/getcate/')
def getcate():
    #获取所有分类
    sql = "select id,name from cates"
    res = db.find_all(sql)
    print(res)
    return jsonify({'code':200,'list':res})

#课程内容
@bp_users.route('/course/')
def course():
    pass
    #where 是用字符串的拼接来查询数据的  也可以用列表 但是要循环
    where = ' where 1=1'
    #根据父类查
    pid = request.args.get('pid')
    if pid:
        where = where + ' and pid='+pid
    #根据是否上线
    online = request.args.get('online')
    if online:
        where = where + ' and online='+online
    #根据状态查询
    status = request.args.get('status')
    if status:
        where = where + ' and status='+status
    #如果三者都有  where 最后就是 and pid=1 and online=1 and status=1 这个样子查询
    #获取全部
    sql = "select * from courses"+where
    print(sql)
    # res = 1
    res = db.find_all(sql)
    return jsonify({'code':200,'list':res})





